package com.android.loveandhate.detector;

import java.util.List;
import java.util.Map;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.Rect;
import android.view.View;

import com.android.loveandhate.R;
import com.android.loveandhate.detector.image.Face;
import com.android.loveandhate.detector.image.FaceDetect;
import com.android.loveandhate.detector.marker.HelpLines;
import com.android.loveandhate.detector.marker.Image;

public class FaceView extends View {
     private FaceDetect faceDetect;
     
     private Paint tmpPaint = new Paint(Paint.ANTI_ALIAS_FLAG);     
     private Image mask;
     
     public FaceView(Context context) {
          super(context);
                              
          tmpPaint.setStyle(Paint.Style.STROKE);
          tmpPaint.setTextAlign(Paint.Align.CENTER);
                    
          faceDetect = new FaceDetect( context );
          faceDetect.findFaces( R.drawable.face );
          
          mask = new Image(context);
          mask.load(R.drawable.kuss_gross);
     }
     
     @Override
     protected void onDraw(Canvas canvas) { 
    	 float xRatio = getWidth()*1.0f / faceDetect.getImageWidth();
    	 float yRatio = getHeight()*1.0f / faceDetect.getImageHeight();
    	 canvas.drawBitmap( faceDetect.getSourceImage(), null , new Rect(0,0,getWidth(),getHeight()),tmpPaint);
    	 
    	 List <Face> faces = faceDetect.getFaces();
    	 
         for (int i = 0; i < faces.size(); i++) {
        	 Face face = faces.get(i);
        	 PointF middlePoint = face.getMiddlePoint();
        	 float distance = face.getDistance();
        	 
        	 if (middlePoint != null) {        		 
        		 Integer factor = 3;
                 Map<Character, Integer> size = mask.getImageSize(mask.getImage());
                 
                 Bitmap resizedImage = mask.getResizedImage((Integer)size.get( 'x' )/factor, (Integer)size.get( 'y' )/factor );
                 Map<Character, Integer> resize = mask.getImageSize(resizedImage);
                 
                 float x = (middlePoint.x*xRatio)-(resize.get('x')/2);
                 float y = (middlePoint.y*yRatio)-(resize.get('y')/2)+distance;
                 
                 HelpLines helpLines = new HelpLines( canvas, distance, middlePoint, xRatio, yRatio);
                 helpLines.drawHeadRect();
                 helpLines.drawEyes();
                 helpLines.horizontalSpit();
                 helpLines.verticalSplit();
                 
                 canvas.drawBitmap(resizedImage, x, y, null);
             }
         }
     }
}
